package com.hcf.project.common.convention.result;

import com.hcf.project.common.convention.errorcode.BaseErrorCode;
import com.hcf.project.common.convention.exception.AbstractException;

import java.util.Optional;

public final class ResultTool {
    /**
     * 构建成功响应
     */
    public static Result<Void> success(){
        return new Result<Void>()
                .setCode(Result.SUCCESS_CODE);
    }

    /**
     * 构建带返回数据的成功响应
     */
    public static <T> Result<T> success(T data){
        return new Result<T>()
               .setCode(Result.SUCCESS_CODE)
               .setData(data);
    }

    /**
     * 构建服务器失败响应
     */
    public static Result<Void> failure(){
        return new Result<Void>()
               .setCode(BaseErrorCode.SERVICE_ERROR.code())
               .setMessage(BaseErrorCode.SERVICE_ERROR.message());
    }

    /**
     * 通过 {@link AbstractException} 构建失败响应
     */
    public static <T> Result<T> failure(AbstractException e){
        // 解决空指针问题
        String errorCode = Optional.ofNullable(e.getCode())
                .orElse(BaseErrorCode.SERVICE_ERROR.code());
        String errorMessage = Optional.ofNullable(e.getMessage())
                .orElse(BaseErrorCode.SERVICE_ERROR.message());
        return new Result<T>()
               .setCode(e.getCode())
               .setMessage(e.getMessage());
    }

    /**
     * 通过 errorCode、errorMessage 构建失败响应
     */
    public static <T> Result<T> failure(String errorCode, String errorMessage){
        return new Result<T>()
               .setCode(errorCode)
               .setMessage(errorMessage);
    }
}
